define(function (require) {
    var $ = require("jquery");
    require("pagination");
    require('angular-ui');
    require('angular-interceptor');

    var util = require("util");
    var ui = require("ui");
    var angular = require("angular");
    var _ = require('underscore');
    require('placeholder');

    angular
		.module('parameter', [
			'ngInterceptor',
			'ngPublicUI',
			'ngPlaceholder'
		])
        .constant('apibe', '/api/')
        .constant('NEED_TOKEN', 'true')
        .constant('apife', 'index.php?r=config/report-config/')
        .factory('url', [
            function () {
                return {
                    //给url添加search字符串
                    addParam: function (url, search) {
                        for (var key in search) {
                            if (search.hasOwnProperty(key) && search[key]) {
                                var connecter = "&";
                                if (url.indexOf('?') === -1) {
                                    connecter = "?";
                                }
                                url += connecter + key + '=' + encodeURIComponent(search[key]);
                            }
                        }
                        return url;
                    },
                    getParam: function (url,param){
                        var query = {};
                        
                        url.replace(/[?&#]([^=]+)=([^&#$]+)/g,function(str,key,val){
                            query[key] = val;
                        });
                        
                        return query[param];
                    }
                };
            }
        ])
        .factory('http', [
            '$http',
            'url',
            'apibe',
            'apife',
            'NEED_TOKEN',
            function ($http, url, apibe, apife, NEED_TOKEN) {
                var requrl = apibe + apife;
                return {
                    get: function (api, search) {
                        search = angular.extend(search || {}, { rnd: Math.random() })
                        api = url.addParam(requrl + api, search);
                        return $http.get(api, { needToken: NEED_TOKEN });
                    },
                    post: function (api, data, search) {
                        var dataMap = [];
                        for (var key in data) {
                            if (data.hasOwnProperty(key)) {
                                var val = data[key];
                                if (angular.isObject(val)) {
                                    val = JSON.stringify(val);
                                }
                                dataMap.push(key + '=' + encodeURIComponent(val));
                            }
                        }
                        data = dataMap.join('&');
                        search = angular.extend(search || {}, { rnd: Math.random() })
                        api = url.addParam(requrl + api, search);
                        return $http.post(api, data, {
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            needToken: NEED_TOKEN
                        });
                    }
                };
            }
        ])
        .factory('reportConfigService', [
            'http',
            function (http) {
                var httpClient = {
                    get: function (api, options) {
                        return http.get(api, options.search)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    return options.success(res);
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            });
                    },
                    post: function (api, options) {
                        return http.post(api, options.data, options.search)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    return options.success(res);
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            });
                    }
                };
                return {
                    getReportConfig: function (options) {
                        return httpClient.get('get', options);
                    },
					updateReportConfig: function (options){
                        return httpClient.post('save', options);						
					},
                    getReportItemConfig: function (){
                        return {
                            "yjkj": [],
                            "rgkj": {
                                "plus": ["dqrg","dqzq"],
                                "minus": ["dqrgdqzq","dqrgdqtf","lsrgdqtf","dqzhuanqdqtf","dqzhiqdqtf"],
                            },
                            "qykj": {
                                "plus": ["dqqy"],
                                "minus": ["dqqydqtf","lsqydqtf"]
                            }
                        };
                    }
                                    
                };
            }
        ])
        .controller('ReportConfigController', [
            '$scope',
            '$rootScope',
            '$compile',
            'reportConfigService',
            'url',
            function ($scope, $rootScope, $compile, service,url) {
				$scope.current = "yjkj";
				               
            	service.getReportConfig({
					search: {},
					success: function (res){
                        $scope.itemConfig = service.getReportItemConfig();
                        if (angular.isArray(res.data.list)){
                            res.data.list = {};
                        }
                        res.data.list = angular.extend({
                            "yjkj": {},
                            "rgkj": {},
                            "qykj": {}
                        },res.data.list);
                        res.data.list['rgkj']['dqrg'] = 1; //当期认购默认为1
                        res.data.list['qykj']['dqqy'] = 1; //当期签约默认显示
						$scope.reportConfig = res.data;                                 
					}
				});
				
				$scope.changeTab = function (tab){
					$scope.current = tab;	
				};
                
                $scope.updateConfig = function (){
                    service.updateReportConfig({
                        data: {
                            type: $scope.current,
                            data: $scope.reportConfig.list[$scope.current]
                        },
                        success: function (res){
                            ui.showSucTip("保存成功");
                        }
                    });
                };
                
                $scope.goBack = function (){
                    var token = url.getParam(location.href,'token');
                    var paramStr = token ? ('&token=' + token) : '';
                    location.href = "../index.html?code=paramsSetting" + paramStr;
                };
                
                $scope.preview = function (){
                    var token = url.getParam(location.href,'token');
                    var paramStr = token ? ('?token=' + token) : '';
                    location.href = "../statistical/report_form.html" + paramStr;
                };
                
                $scope.getItemDisplay = function (type,item){
                    if (type !== "rgkj") {
                        return true;
                    }
                    if (item === "dqzhiqdqtf") {
                        return $scope.reportConfig.list['rgkj']['dqrg'] == 1 && $scope.reportConfig.list['rgkj']['dqzq'] == 1;
                    }
                    if (item === "dqzhuanqdqtf"){
                        return $scope.reportConfig.list['rgkj']['dqrgdqzq'] != 1;
                    }
                    if(item === 'dqrgdqzq'){
                        return $scope.reportConfig.list['rgkj']['dqzhuanqdqtf'] != 1;
                    }
                    return true;    
                };
                
                $scope.toggleSelect = function (type,item){
                    if (type === 'qykj' && item === 'dqqy') {
                        return;
                    }
                    $scope.reportConfig.list[type][item] = ($scope.reportConfig.list[type][item] ? 0 : 1);
                    $scope.refreshEquation($scope.reportConfig);
                };
                
                $scope.setSelect = function (type,curr,other){
                    $scope.reportConfig.list[type][curr] = 1;
                    $scope.reportConfig.list[type][other] = 0;
                    
                    $scope.yjkjEquation = $scope[curr + 'kjEquation'];
                };
                
                $scope.setRgkj = function(dqrg,dqzq) {
                    $scope.reportConfig.list['rgkj']['dqrg'] = dqrg;
                    $scope.reportConfig.list['rgkj']['dqzq'] = dqzq;
                    if(dqrg === 1 && dqzq === 0){
                        $scope.reportConfig.list['rgkj']['dqzhiqdqtf'] = 0;
                    }
                    $scope.refreshEquation($scope.reportConfig);
                }
                
                $scope.getConfigEffectUrl = function (type){
                    var token = url.getParam(location.href,'token');
                    var paramStr = token ? ('?token=' + token) : '';
                    return "config_effect.html" + paramStr + "&type=" + type;
                };
                
                $scope.refreshEquation = function (){
                    angular.forEach($scope.itemConfig,function (val,key){
                        if (val.plus && val.minus) {
                            var equation;
                            var plus = [];
                            var minus = [];
                            for (var i = 0; i < val.plus.length; i++) {
                                var item = val.plus[i];
                                if ($scope.reportConfig.list[key][item] == 1) {
                                    plus.push($scope.reportConfig.config[item]);                                      
                                }                               
                            }
                        
                            for (var i = 0; i < val.minus.length; i++) {
                                var item = val.minus[i];
                                if ($scope.reportConfig.list[key][item] == 1) {
                                    minus.push($scope.reportConfig.config[item]);                                      
                                }                               
                            }
                            
                            equation = [plus.join('+').split(" "),minus.join('-').split(" ")].join('-');
                            $scope[key + 'Equation'] = equation.replace(/-$/,'');
                        }
                    });
                    
                    
                    if ($scope.reportConfig.list['yjkj'].rg && $scope.reportConfig.list['yjkj'].rg == 1) {
                        $scope.yjkjEquation = $scope['rgkjEquation'];
                    } else if ($scope.reportConfig.list['yjkj'].qy && $scope.reportConfig.list['yjkj'].qy == 1) {
                        $scope.yjkjEquation = $scope['qykjEquation'];
                    }
                };
                
                $scope.$watch('reportConfig',function (val){
                    if (val) {
                        $scope.refreshEquation(val);
                        
                    }
                });
            }
        ])

    angular.element(document).ready(function () {
        angular.bootstrap(document, ['parameter']);
    });
});
